/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"log"
	"strings"

	"baliance.com/gooxml/document"
	"github.com/spf13/cobra"
)

// checkCmd represents the check command
var checkCmd = &cobra.Command{
	Use:   "check",
	Short: "./wordCheck check xxx/xxx/xxx.docx  a b c ",
	Long: `示例:
./wordCheck check xxx/xxx/xxx.docx  a b c

第一个参数是 word 文档路径,后面是要检查的字符串,可同时输入多个`,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) < 2 {
			log.Fatal("至少输入 2 个参数")
			return
		}
		doc, err := document.Open(args[0])
		if err != nil {
			return
		}

		var containWords []string
		for _, p := range doc.Paragraphs() {
			for _, run := range p.Runs() {
				// log.Print(ii, run.Text())
				isContain, words := CheckStringInRun(run.Text(), args[1:])
				if isContain {
					containWords = mergeArr(containWords, words)
				}

			}
		}
		if len(containWords) != 0 {
			log.Print("\n")
			log.Print("####### Word Check#######")
			log.Print("\n")
			log.Printf("在 [%s] 里找到下面这些字符串:", args[0])
			log.Print(uniqueStringList(containWords))
		} else {
			log.Print("什么都没找到")
		}
	},
}

func init() {
	rootCmd.AddCommand(checkCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// checkCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// checkCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func CheckFileExsited(FilePath string) (err error, doc *document.Document) {
	doc, err = document.Open("ml.docx")
	if err != nil {
		log.Fatalf("error opening document: %s", err)
	}
	return
}

func CheckStringInRun(runContent string, checkWords []string) (isContain bool, containWords []string) {
	for _, word := range checkWords {
		if find := strings.Contains(runContent, word); find {
			containWords = append(containWords, word)
			isContain = true
		}
	}
	if len(containWords) == 0 {
		return false, containWords
	}
	return true, containWords
}

func uniqueStringList(m []string) []string {
	d := make([]string, 0)
	tempMap := make(map[string]bool, len(m))
	for _, v := range m { // 以值作为键名
		if tempMap[v] == false {
			tempMap[v] = true
			d = append(d, v)
		}
	}
	return d
}

//　合并数组
func mergeArr(a, b []string) []string {
	var arr []string
	for _, i := range a {
		arr = append(arr, i)
	}
	for _, j := range b {
		arr = append(arr, j)
	}
	return arr
}
